package org.example.Config;


import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.example.Handler.ComfyuiMessageHandler;
import org.example.api.ComfyuiApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;

import static org.example.core.Service.impl.Text2ImageServiceImpl.COMFYUI_CLIENT_ID;

@Configuration
public class ComfyuiConfig {

    @Bean
    public ComfyuiApi comfyuiApi(){
        HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okhttpclient=new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.MINUTES) // 连接超时时间
                .readTimeout(30, TimeUnit.MINUTES)   // 读取超时时间
                .writeTimeout(30, TimeUnit.MINUTES)  // 写入超时时间
                .build();

        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://192.168.100.129:8188/")
                .client(okhttpclient)
                .addConverterFactory(JacksonConverterFactory.create())
                .build();

        ComfyuiApi comfyuiApi = retrofit.create(ComfyuiApi.class);
        return comfyuiApi;
    }

    /**
     * 声明一个ws客户端并生效
     * @param handler
     * @return
     */
    @Bean

    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler handler){
        WebSocketClient webSocketClient=new StandardWebSocketClient();
       String url = "ws://192.168.100.129:8188/ws?clientId="+COMFYUI_CLIENT_ID;
        WebSocketConnectionManager webSocketConnectionManager=new WebSocketConnectionManager(
                webSocketClient,handler,url
                );
        webSocketConnectionManager.start();
        return  webSocketConnectionManager;
    }

}
